#include <sum_dac.h>
#include <sum_gpio.h>
#include <sum_rcu.h>

#define GAP_2_POWER 9

// RCU中将GPIOA和DAC上电
static void _enable_gpio_dac(void) {
	rcu_apb1_24_31_s apb1_24_31 = {
		.DAC = 1,
	};
	rcu_apb1_24_31_en_di(apb1_24_31);

	rcu_apb2_0_7_s apb2_0_7 = {
		.GPIOA = 1,
	};
	rcu_apb2_0_7_en_di(apb2_0_7);
}

// 配置GPIO的A4、A5为模拟模式
static void _setup_gpio(void) {
	gpio_ctl_0_7_s gpioa_ctl_0_7 = {
		.pin4_ctl = GPIO_ANALOG,
		.pin5_ctl = GPIO_ANALOG,
	};
	gpio_setup_pin_0_7(GPIOA_Q, gpioa_ctl_0_7);
}

// 初始化DAC
static void _init_dac(void) {
	dac_ctl_one_s ctl_one = {
		.dac_en = 1,
		.buf_dis = 0,
		.trig_en = 0,
		.noise_wave_mode = 0,
		.dma_en = 0,
	};
	dac_ctl_expl_s ctl = {
		.dac_ctl_a[0] = ctl_one,
		.dac_ctl_a[1] = ctl_one,
	};
	dac_setup(ctl);
}

__attribute__((noreturn, section(".MAIN"))) void user_main(void) {
	// 未定义全局变量和静态局部变量，因此不需要scatter_load。
	// mem_scatter_load();
	_enable_gpio_dac();
	_setup_gpio();
	_init_dac();

	for (u32_s i = 0;; i++) {
		union {
			struct {
				u32_s : GAP_2_POWER;
				i32_s value : 12;
			} st;
			u32_s u;
		} su = {
			.u = i,
		};
		i32_s value = su.st.value;

		// 输出的digital为value绝对值。因此输出值在0到2048之间。
		u32_s sig = value >> 31;
		u32_s digital = (value ^ sig) - sig;
		dac_concurrent_set_12_bit_digital_by_u16(digital, digital);
	}
}
